/* eslint-disable react/no-unstable-nested-components */
/* eslint-disable react-native/no-inline-styles */

import React, {useRef, useState} from 'react';
import {View, Text, Colors, Checkbox, Image} from 'react-native-ui-lib';
import {get, update} from '@/utils/request';
import {RefreshControl, ScrollView, FlatList} from 'react-native';
import {useRequest} from 'ahooks';
import {useDispatch, useSelector} from 'react-redux';
import ProjectItem from '@/components/ProjectItem';
import Octicons from 'react-native-vector-icons/Octicons';
import Ionicons from 'react-native-vector-icons/Ionicons';
import Entypo from 'react-native-vector-icons/Entypo';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import AntDesign from 'react-native-vector-icons/AntDesign';
import {TouchableWithoutFeedback} from 'react-native';
import Actions from '@/components/Actions';

function Header({data, onSelect, curProject, setAction, refreshAsync}) {
  const Prefix = global.file;

  return (
    <ScrollView horizontal>
      <View height={58} width={999} row style={{gap: 8}}>
        {data?.map?.((item, index) => {
          const collectoption = {
            // 0: {
            //   label: '星标',
            //   onPress: async () => {
            //     let res = await update('/userProject', {
            //       projectId: item?.id,
            //       isCollection: 1,
            //     });
            //     if (res.code === 0) {
            //       refreshAsync();
            //     }
            //   },
            // },
            // 1: {
            //   label: '取消星标',
            //   onPress: async () => {
            //     let res = await update('/userProject', {
            //       projectId: item?.id,
            //       isCollection: 0,
            //     });
            //     if (res.code === 0) {
            //       refreshAsync();
            //     }
            //   },
            // },
          };

          return (
            <TouchableWithoutFeedback
              key={index}
              onPress={() => {
                onSelect(curProject?.id === item?.id ? null : item);
              }}
              onLongPress={() => {
                setAction(s => ({
                  ...s,
                  visible: true,
                  options: [
                    {
                      label: '取消置顶',
                      onPress: async () => {
                        let res = await update('/userProject', {
                          projectId: item?.id,
                          isTop: 0,
                        });
                        if (res.code === 0) {
                          refreshAsync();
                        }
                      },
                    },
                    // collectoption[item?.isCollection],
                  ],
                }));
              }}>
              <View
                width={58}
                height={58}
                center
                style={{
                  borderRadius: 8,
                  backgroundColor:
                    curProject?.id === item?.id
                      ? Colors.primaryColor
                      : Colors.colorCardBg,
                }}>
                {item.logoUrl ? (
                  <Image
                    source={{
                      uri: Prefix + item.logoUrl,
                    }}
                    errorSource={require('../../assets/logo_default.png')}
                    aspectRatio={1}
                    style={{
                      borderRadius: 6,
                      width: 54,
                      height: 54,
                      borderColor: Colors.colorCardBg,
                      overflow: 'hidden',
                      backgroundColor: Colors.colorCardBg,
                    }}
                  />
                ) : (
                  <View
                    center
                    width={54}
                    height={54}
                    style={{
                      borderRadius: 6,
                      backgroundColor: Colors.colorCardBg,
                    }}>
                    <Text heading>{item?.projectName?.charAt(0)}</Text>
                  </View>
                )}
              </View>
            </TouchableWithoutFeedback>
          );
        })}
        {/* {data?.length === 0 && (
          <View
            width={58}
            height={58}
            center
            style={{
              borderRadius: 8,
              backgroundColor: Colors.colorCardBg,
            }}>
            <Image
              source={require('../../assets/nodata.png')}
              aspectRatio={1}
              style={{
                borderRadius: 8,
                width: 56,
                height: 56,
                borderColor: Colors.colorCardBg,
                overflow: 'hidden',
                backgroundColor: 'transparent',
              }}
            />
          </View>
        )} */}
      </View>
    </ScrollView>
  );
}

function Projects({dialog, setDialog, navigation}) {
  const searchArr = [
    {
      label: '全部',
      key: '-1',
      color: Colors.colorTextBase,
      icon: style => <Ionicons name="apps" size={24} style={style} />,
    },
    {
      label: '未开始',
      key: '0',
      color: '#ea7267',
      icon: style => <Octicons name="dash" size={24} style={style} />,
    },
    {
      label: '进行中',
      key: '1',
      color: '#229c9e',

      icon: style => <Entypo name="circular-graph" size={24} style={style} />,
    },
    {
      label: '已完成',
      key: '2',
      color: '#3283c6',

      icon: style => <Entypo name="circle" size={24} style={style} />,
    },
    {
      label: '已延期',
      key: '3',
      color: 'red',
      icon: style => (
        <MaterialCommunityIcons name="timer-off" size={26} style={style} />
      ),
    },
  ];
  const flatListRef = useRef();
  const [params, setParams] = useState({
    status: '-1',
    isCollection: null,
  });

  const [action, setAction] = useState({
    visible: false,
    onDismiss: () => {
      setAction(s => ({
        ...s,
        visible: false,
      }));
    },
  });

  const {data, loading, refresh, refreshAsync} = useRequest(
    async () => {
      const extra =
        params.status === '-1' ? {status: null} : {status: params.status};
      let res = await get('/project', {
        ...params,
        ...extra,
      });
      return res?.data?.dataList;
    },
    {
      refreshDeps: [params],
    },
  );

  const [mine, setMine] = useState(false);

  const curProject = useSelector(state => state.curProject);
  const userInfo = useSelector(state => state.userInfo);

  const dispatch = useDispatch();

  return (
    <View flex-1>
      <Actions action={action} setAction={setAction} />
      <View padding-18 paddingB-12>
        <View row spread centerV>
          <TouchableWithoutFeedback
            onPress={() => {
              navigation.goBack();
            }}>
            <View row left style={{gap: 8}} flex-1 centerV>
              <AntDesign
                name="left"
                size={22}
                style={{color: Colors.colorTextBase}}
              />
              <View bottom row>
                <Text heading marginR-8 numberOfLines={1}>
                  {curProject?.projectName}
                </Text>
                <Text
                  body
                  numberOfLines={1}
                  style={{
                    color:
                      searchArr[
                        searchArr?.map(it => it.key).indexOf(params?.status)
                      ]?.color,
                  }}>
                  {
                    searchArr[
                      searchArr?.map(it => it.key).indexOf(params?.status)
                    ]?.label
                  }
                </Text>
              </View>
            </View>
          </TouchableWithoutFeedback>
        </View>
        <View row marginV-10>
          <View row flex-1 style={{gap: 10}}>
            {searchArr?.map(item => {
              return (
                <TouchableWithoutFeedback
                  key={item.key}
                  onPress={() => {
                    setParams(s => ({...s, status: item.key}));
                  }}>
                  <View
                    width={36}
                    height={36}
                    center
                    br20
                    style={{
                      backgroundColor:
                        params?.status === item.key
                          ? Colors.colorCardBg
                          : 'transparent',
                    }}>
                    {item?.icon?.({
                      color:
                        params?.status === item.key
                          ? item.color
                          : Colors.bodyColor,
                    })}
                  </View>
                </TouchableWithoutFeedback>
              );
            })}
          </View>
          <Checkbox
            color={Colors.primaryColor}
            value={mine}
            label="我的"
            onValueChange={() => {
              setMine(!mine);
            }}
            labelStyle={{marginLeft: 8}}
          />
        </View>
        <Header
          data={
            data
              ?.filter?.(it => it?.isTop === 1)
              .filter?.(it => {
                if (!mine) {
                  return true;
                } else {
                  return userInfo?.id === it?.projectUserId;
                }
              }) ?? []
          }
          setAction={setAction}
          onSelect={cur => {
            dispatch?.({
              type: 'CHANGE_CURPROJECT',
              curProject: cur,
            });
          }}
          curProject={curProject}
          refreshAsync={refreshAsync}
        />
      </View>
      {data
        ?.filter?.(it => it?.isTop !== 1)
        .filter?.(it => {
          if (!mine) {
            return true;
          } else {
            return userInfo?.id === it?.projectUserId;
          }
        })?.length === 0 && (
        <View flex-1 top center>
          <Image
            source={require('../../assets/nodata.png')}
            aspectRatio={1}
            style={{
              borderRadius: 8,
              width: 88,
              height: 88,
              borderColor: Colors.colorCardBg,
              overflow: 'hidden',
              backgroundColor: 'transparent',
            }}
          />
          <Text subheading>暂无数据</Text>
        </View>
      )}
      <FlatList
        style={{paddingHorizontal: 18}}
        // ListHeaderComponent={
        // }
        ref={flatListRef}
        data={
          data
            ? data
                ?.filter?.(it => it?.isTop !== 1)
                .filter?.(it => {
                  if (!mine) {
                    return true;
                  } else {
                    return userInfo?.id === it?.projectUserId;
                  }
                })
            : []
        }
        renderItem={({item}) =>
          ProjectItem({item, refreshAsync, curProject, dispatch})
        }
        keyExtractor={item => item.id.toString()}
        refreshControl={
          <RefreshControl refreshing={loading} onRefresh={refresh} />
        }
      />
    </View>
  );
}

export default Projects;
